
from sys import _getframe as stackFrame
from colorama import Fore, Back, Style
from prettytable import PrettyTable
from datetime import datetime
from os import system
import sqlite3
import json



#NOTE: read mode in read function








class connector():

	def jsonConfInit(self, name):
		try:
			with open(name, 'r') as jsf:
				config = json.load(jsf) # импорт конфига
				self.language = config["language"]
		except FileNotFoundError as e:
			raise
		else:
			pass
		finally:
			with open('./defaultConfigs/defaultConfig.json', 'r') as jsf:
				config = json.load(jsf) # импорт конфига
				self.language = config["language"]



	def getTranslations(self, lang):

		with open('./defaultConfigs/language/' + lang + '.json', 'r') as f:
			config = json.load(f)
			self.help_c = config["help_c"]

			self.areYouSure_c = config ["areYouSure_c"]
			self.colomnsName = config ["colomnsName"]
			self.delmenu_c = config["delmenu_c"]
			self.update = config["update"]
			self.help_c = config["help_c"]
			self.bye = config["bye"]

		return {
			'areYouSure_c': self.areYouSure_c,
			'colomnsName': self.colomnsName,
			'delmenu_c': self.delmenu_c,
			'update': self.update,
			'help_c': self.help_c,
			'bye': self.bye,
		}

	def getVar(self):
		return self.connDB, self.cursor

	def __init__(self, name, jsonName):
		self.name = name # копирование переменной в переменную объекта
		self.connDB = sqlite3.connect(jsonName) # конект с бд
		self.cursor = self.connDB.cursor() # инициализация курсора
		self.jsonConfInit(name)


	def __del__(self):
		self.connDB.close()# закрытие конекта




class shellMenu():

	def __init__(self, var, setTranslations, quitPrint):
		self.areYouSure_c = setTranslations['areYouSure_c']
		self.colomnsName = setTranslations['colomnsName']
		self.delmenu_c = setTranslations['delmenu_c']
		self.update = setTranslations['update']
		self.help_c = setTranslations['help_c']
		self.bye = setTranslations['bye']
		self.quitPrint = quitPrint
		self.connDB = var[0]
		self.cursor = var[1]

	# собирательная функция
	def menu(self):
		self.helper()
		while True:
			print(self.pwDir(4), end=' ')
			userInput = input()
			if userInput == '':
				pass
			elif userInput == 'r':
				self.read()
			elif userInput == 'w':
				self.write(userInput)
			elif userInput == 'd':
				self.delMenu(userInput)
			elif userInput == 'u':
				self.upDate(userInput)
			elif userInput == 'q':
				self.quit(self.quitPrint)
			elif userInput == 'help':
				self.helper()
			elif userInput == 'clear':
				self.clearShell()
			else:
				print( 'Unknown command: ' + userInput + '\n' +'Enter \'help\'' )

	# меню удаления
	def upDate(userinput):

		print( 'test help' )

		while True:
			userinput = str( input( enter + upmenu ) )# input shell
			if userinput != 'q':
				if userinput == 'Execute':
					checkUp(userinput)
				elif userinput == 'Edit':
					changeContent(userinput)
				elif userinput == 'Group':
					egitGroup(userinput)
			elif userinput == 'q':
				break
			else:
				print( 'Unknown command: ' + userinput + '\n' +'Enter \'help\'' )

	# рабочая дериктория
	def pwDir(self, count): # numbering as in lists

		tree = {
			'menu': '>SLM>',
			'write': 'input>',
			'delMenu': 'delite>',
			'upDate': 'update>',
			'read': 'read>',
		}
		outDir = ''
		dirs = []
		try:
			for i in range(count):
				pwd = (str(stackFrame(i)).split(', code '))[1][0:-1]
				dirs.append(pwd)
		except:
			dirs.reverse()
			dirs.remove('<module>')
			dirs.remove('pwDir')
			for j in range(len(dirs)):
				outDir += tree[dirs[j]]

		return outDir


	# очиска терминала
	def clearShell(self): # system == os P.S see import block
		system(['clear'][system.name == system.sys.platform])

	# хелп
	def helper(self):
		help_c = self.help_c["work_mode"] + '\n' + Fore.GREEN + self.help_c["read"] + Fore.BLUE + '\n' + self.help_c["write"] + Fore.YELLOW + '\n'+ self.help_c["update"] + Fore.MAGENTA + '\n' + self.help_c["deleteAll"] + '\n'+ Fore.RED + self.help_c["exit"] + Fore.RESET 
		print( help_c )


	# чтение наших записей
	def read(self, mode='0'):

		if mode:
			command = ' SELECT * FROM notes WHERE status = 0 '
		elif not mode:
			command = ' SELECT * FROM notes '


		table = PrettyTable() # создаем экземпляр класса PretyTable
		self.cursor.execute(command) # выбираем все записи
		result = self.cursor.fetchall()
		table.field_names = [ self.colomnsName['id'], self.colomnsName['content'], self.colomnsName['time'], self.colomnsName['date'], self.colomnsName['status'], self.colomnsName['group']  ] # прописываем столбцы
		for item in result: # собираем вывод
			table.add_row( [ item[0], item[1], item[2], item[3], item[4], item[5] ] )
		table.align = 'c'
		table.align['Id'] = 'r'
		print( table ) # распечатываем

	# меню удаления записей
	def delMenu(self, userInput):
		print( 'test help' )

		while True:
			userInput = str( input( enter + delmenu ) )# input shell
			if userInput != 'q':
				if userInput == 'del':
					delete(userInput)
				elif userInput == 'delAll':
					deleteAll(userInput)
			elif userInput == 'q':
				break
			else:
				print( 'Unknown command: ' + userInput + '\n' +'Enter \'help\'' )

	# построное удаление
	def delete(self, userInput):
		read()
		userInput = str(input( delmenu_c['delete_c'] ))
		toBase = [(userInput)]
		cursor.execute(' DELETE FROM notes WHERE id = ? ', toBase)
		connDB.commit()

	# полное удаление
	def deleteAll(self, userInput):
		areYouSure = str( input( areYouSure_c ) )# подтвеждение
		if areYouSure == 'yes':
			cursor.execute(' DELETE FROM notes ')# удаление файла
			connDB.commit()
		else:
			pass

	def quit(self, foo=None):
		print(self.bye)
		if foo == None:
			pass
		else:
			print(foo)
		exit(0)